package com.gmrz.uap.job;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.datastatistics.DataStatisticsService;
import com.gmrz.uap.model.Authenticators;
import com.gmrz.uap.model.DataStatistics;
import com.gmrz.uap.util.DateUtil;
import com.jfinal.kit.StrKit;
import org.joda.time.DateTime;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.List;

/**
 * 在每隔一段时间来计算今天注册的统计信息
 */
public class RegisterStatisticsDayJob implements Job {
    private static boolean lock = false;
    public void execute(JobExecutionContext context) throws JobExecutionException {

        try {//根据随机生成的随机毫秒数来进行休眠
            Thread.sleep(DataStatisticsService.me.getRandomSleepMinutes());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(!lock) {
            String key = TaskConst.REGISTERSTATISTICSDAYJOB_CACHE_KEY;
            key = key + DateUtil.getToday();
            boolean flag = false;
            try {
                lock = true;
                flag = AmmsCacheUtil.getCacheStoreService().tryGetDistributedLock(key,TaskConst.JOB_CACHE_VALUE,TaskConst.AAIDSTATISTICSDAYJOB_CACHE_TiME);
                if(flag) {
                    //获取当前统计类型的最新日期
                    DataStatistics dataStatistics = new DataStatistics();
                    dataStatistics.setStaType(TaskConst.STATISTICS_KEY_REGCOUNT);
                    String lastDate = DataStatistics.dao.findLatestDate(dataStatistics);


                    if (StrKit.isBlank(lastDate)) {//如果日期为空则将获取需要统计的全部日期
                        DateTime earliestDate = Authenticators.dao.getEarliestDate();//数据库最早插入数据的时间
                        List<String> dateList = DataStatisticsService.me.differDays(earliestDate);
                        for (String date : dateList) {
                            DataStatisticsService.me.regStatistics(new DateTime(date));
                        }
                    } else {
                        List<String> dateList = DataStatisticsService.me.differDays(new DateTime(lastDate));
                        for (String date : dateList) {
                            DataStatisticsService.me.regStatistics(new DateTime(date));
                        }
                    }
                }
            } finally {
                lock = false;
                if(flag){
                    AmmsCacheUtil.getCacheStoreService().releaseDistributedLock(key,TaskConst.JOB_CACHE_VALUE);
                }
            }
        }
    }
}
